package cn.com.ddapp.ddm.ui.mine;

import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.ColorDrawable;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.support.v7.app.AlertDialog;
import android.text.TextUtils;
import android.view.Display;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;
import com.bumptech.glide.Glide;
import com.google.gson.Gson;
import java.io.File;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.com.ddapp.ddm.AppConfig;
import cn.com.ddapp.ddm.R;
import cn.com.ddapp.ddm.api.OKUtilAPI;
import cn.com.ddapp.ddm.base.BaseActivity;
import cn.com.ddapp.ddm.base.BaseApplication;
import cn.com.ddapp.ddm.bean.Entity;
import cn.com.ddapp.ddm.bean.mine.MyWheelView;
import cn.com.ddapp.ddm.bean.mine.OnMyWheelScrollListener;
import cn.com.ddapp.ddm.inter.OkUtilCallback;
import cn.com.ddapp.ddm.ui.empty.EmptyLayout;
import cn.com.ddapp.ddm.util.SPUtils;
import cn.com.ddapp.ddm.util.ToastUtil;
import cn.com.ddapp.ddm.widget.CircleImageView;
import cn.com.ddapp.ddm.widget.date.NumericWheelAdapter;

public class PersonCenterActivity extends BaseActivity implements View.OnClickListener{

    @BindView(R.id.back)
    ImageView back;
    @BindView(R.id.titletext)
    TextView titletext;
    View view;
    @BindView(R.id.right)
    ImageView right;
    @BindView(R.id.headimg)
    CircleImageView headimg;
    @BindView(R.id.nickname)
    TextView nickname;
    @BindView(R.id.sex)
    TextView sex;
    @BindView(R.id.birthday)
    TextView birthday;
    @BindView(R.id.error_layout)
    EmptyLayout mEmptyLayout;
    @BindView(R.id.right_text)
    TextView rightText;

    String userName;
    String userBirth;
    String userheadImg;
    int userSex;

    private String theLarge, theThumbnail;
    PopupWindow menuWindow;
    private MyWheelView year;
    private MyWheelView month;
    private MyWheelView day;

    String path;


    public static final int ACTION_TYPE_ALBUM = 0;//相册
    public static final int ACTION_TYPE_PHOTO = 1;//拍照

    public static final int TAKE_PHOTO_REQUEST_CODE = 1001;
    public static final int SELECT_FROM_GALLERY_REQUEST_CODE = 2001;
    public static final int CROP_PICTURE = 3001;
    public static final int TONICKNAME = 101;

    private LayoutInflater inflater = null;

    String userId;
    Bitmap mineBitmap;


    @Override
    public void initView() {
        titletext.setText(R.string.person);
        rightText.setText(R.string.end);
        rightText.setVisibility(View.VISIBLE);
        back.setOnClickListener(this);
        rightText.setOnClickListener(this);
    }

    @Override
    public void initData() {
        userId=SPUtils.getStringData(PersonCenterActivity.this, SPUtils.USERID);
    }

    @Override
    public int getContentViewId() {
        return R.layout.activity_person_center;
    }

    @Override
    protected String getFragmentTag() {
        return null;
    }
    private Uri uri;
    @OnClick({R.id.addressL,R.id.nicknameL,R.id.sexL,R.id.headimgL,R.id.birthdayL})
    public void onClick(View view){
        Intent intent;
        String curName=nickname.getText().toString();
        switch (view.getId()){
            case R.id.addressL :
                intent = new Intent(this,AddressActivity.class);
                intent.putExtra("flag","selenow");
                startActivity(intent);
                break;
            case R.id.nicknameL :
                intent = new Intent(this, NickNameActivity.class);
                intent.putExtra("userName", nickname.getText().toString());
                startActivityForResult(intent, TONICKNAME);
                break;
            case R.id.headimgL :
                showSelectPictureDialog();
                break;
            case R.id.birthdayL :
                showPopwindow(getDataPick());// 弹出日期选择器
                break;
            case R.id.sexL :
                final String[] items = {"女", "男"};
                if (userSex==1){
                    SPUtils.setStringData(getApplicationContext(), SPUtils.USERSEX, "男");
                }
                if (userSex==0){
                    SPUtils.setStringData(getApplicationContext(), SPUtils.USERSEX, "女");
                }

                new AlertDialog.Builder(this).setSingleChoiceItems(items, userSex, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        String item = items[i];//w,m
                        SPUtils.setStringData(getApplicationContext(), SPUtils.USERSEX, item);//w,m
                    }
                }).setNegativeButton(
                        "确定", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialogInterface, int i) {
                                sex.setText(SPUtils.getStringData(getApplicationContext(), SPUtils.USERSEX));//w,m
                                if (sex.getText().toString().equals("男")) {
                                    userSex = 1;//m
                                } else userSex = 0;//w
                                dialogInterface.dismiss();
                            }
                        }).show();
                break;
            //从相册选择
            case R.id.select_picBox:
                Intent selectFromGallery_intent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                startActivityForResult(selectFromGallery_intent, SELECT_FROM_GALLERY_REQUEST_CODE);
                dialog.dismiss();
                break;
            //拍照
            case R.id.cup_pic:
                Intent takePhoto_intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                // 指定图片储存路径
                uri = Uri.fromFile(getTempImage());
                takePhoto_intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
                startActivityForResult(takePhoto_intent, TAKE_PHOTO_REQUEST_CODE);
                dialog.dismiss();
                break;
            case R.id.cancle:
                dialog.dismiss();
                break;
            case R.id.back :
                finish();
                break;
            case R.id.right_text :
                try {
                OkUtilCallback callback = new OkUtilCallback() {
                    @Override
                    public void onMyResponse(String response, int id) {
                        Gson gson = new Gson();
                        Entity entity = gson.fromJson(response, Entity.class);
                        if ((!AppConfig.RESULT_OK.equalsIgnoreCase(entity.getResult())) && entity.getLogin()) {
                            mEmptyLayout.setErrorType(EmptyLayout.NO_LOGIN);
                        } else if ((!AppConfig.RESULT_OK.equalsIgnoreCase(entity.getResult()))) {
                            BaseApplication.getIntstance().showToast(entity.getResult(), Toast.LENGTH_SHORT, 0, Gravity.TOP);
                        } else if ((AppConfig.RESULT_OK.equalsIgnoreCase(entity.getResult()))) {
                            Intent intent1 = new Intent();
                            Bundle bundle = new Bundle();
                            bundle.putString("userName", userName);
                            bundle.putParcelable("photo", bitmap);
                            intent1.putExtras(bundle);
                            setResult(2, intent1);
                            finish();
                        }
                    }
                };
                if (TextUtils.isEmpty(path)){
                    HashMap<String,List<File>> files = null;
                        OKUtilAPI.file(OKUtilAPI.updateUser, "userId=" + userId + "&sex=" + userSex + "&nickName=" + URLEncoder.encode(curName, "utf-8")+ "&birthDay=" + userBirth, callback,files);
                }else {
                    HashMap<Integer,List<File>> fileMap = new HashMap<>();
                    List<File> fileList=new ArrayList<File>();
                    fileList.add(new File(path));
                    fileMap.put(1,fileList);
                    HashMap<String,List<File>> files = new HashMap<>();
                    for(Integer position : fileMap.keySet()){
                        files.put("headImg",fileMap.get(position));
                    }
                    OKUtilAPI.file(OKUtilAPI.updateUser, "userId=" + userId + "&sex=" + userSex + "&nickName=" +  URLEncoder.encode(curName, "utf-8") + "&birthDay=" + userBirth, callback,files);
                }
                } catch (Exception e) {
                    e.printStackTrace();
                }
                break;
        }
    }


    private View getDataPick() {
        Calendar c = Calendar.getInstance();
        final int curYear = c.get(Calendar.YEAR);
        final int curMonth = c.get(Calendar.MONTH) + 1;// 通过Calendar算出的月数要+1
        final int curDate = c.get(Calendar.DATE);
        final View view = inflater.inflate(R.layout.datapick, null);

        year = (MyWheelView) view.findViewById(R.id.year);
        year.setAdapter(new NumericWheelAdapter(1950, curYear));
        year.setLabel("年");
        year.setCyclic(true);
        year.addScrollingListener(scrollListener);

        month = (MyWheelView) view.findViewById(R.id.month);
        month.setAdapter(new NumericWheelAdapter(1, 12));
        month.setLabel("月");
        month.setCyclic(true);
        month.addScrollingListener(scrollListener);

        day = (MyWheelView) view.findViewById(R.id.day);
        initDay(curYear, curMonth);
        day.setLabel("日");
        day.setCyclic(true);

        year.setCurrentItem(curYear - 1950);
        month.setCurrentItem(curMonth - 1);
        day.setCurrentItem(curDate-1);

        Button bt = (Button) view.findViewById(R.id.set);
        bt.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                SimpleDateFormat sdf=new SimpleDateFormat("yyyyMMdd");
                final String curTime=sdf.format(new Date());
                String str=null;
                StringBuffer buffer=new StringBuffer();
                StringBuffer dayBuffer=new StringBuffer();
                if( ( ((month.getCurrentItem()+1) !=10) && ((month.getCurrentItem()+1) !=11) && ((month.getCurrentItem()+1) !=12)) && ((day.getCurrentItem()+1) ==1 || (day.getCurrentItem()+1) ==2 || (day.getCurrentItem()+1) ==3 || (day.getCurrentItem()+1) ==4 || (day.getCurrentItem()+1) ==5 || (day.getCurrentItem()+1) ==6 || (day.getCurrentItem()+1) ==7 || (day.getCurrentItem()+1) ==8    || (day.getCurrentItem()+1) ==9)  ){
                    buffer.append("0").append(month.getCurrentItem()+1);
                    dayBuffer.append("0").append(day.getCurrentItem()+1);
                    str = (year.getCurrentItem()+1950) + "-"+ buffer+"-"+dayBuffer;
                }
                else if( ( ((month.getCurrentItem()+1) !=10) && ((month.getCurrentItem()+1) !=11) && ((month.getCurrentItem()+1) !=12) )  &&  ((day.getCurrentItem()+1) !=1 && (day.getCurrentItem()+1) !=2 && (day.getCurrentItem()+1) !=3 && (day.getCurrentItem()+1) !=4 && (day.getCurrentItem()+1) !=5 && (day.getCurrentItem()+1) !=6 && (day.getCurrentItem()+1) !=7 && (day.getCurrentItem()+1) !=8 && (day.getCurrentItem()+1) !=9 )){
                    buffer.append("0").append(month.getCurrentItem()+1);
                    str = (year.getCurrentItem()+1950) + "-"+ buffer+"-"+(day.getCurrentItem()+1);
                }else if(( (month.getCurrentItem()+1) ==10 || (month.getCurrentItem()+1)==11 || (month.getCurrentItem()+1)==12) && ((day.getCurrentItem()+1) !=1 && (day.getCurrentItem()+1) !=2 && (day.getCurrentItem()+1) !=3 && (day.getCurrentItem()+1) !=4 && (day.getCurrentItem()+1) !=5 && (day.getCurrentItem()+1) !=6 && (day.getCurrentItem()+1) !=7 &&     (day.getCurrentItem()+1) !=8  && (day.getCurrentItem()+1) !=9) ){
                    str = (year.getCurrentItem()+1950) + "-"+ (month.getCurrentItem()+1)+"-"+(day.getCurrentItem()+1);
                }else {
                    dayBuffer.append("0").append(day.getCurrentItem()+1);
                    str = (year.getCurrentItem()+1950) + "-"+ (month.getCurrentItem()+1)+"-"+dayBuffer;
                }
                String nex[]=str.split("-");
                int pre=Integer.parseInt(nex[0]+nex[1]+nex[2]);
                if(pre>Integer.parseInt(curTime)){
                    ToastUtil.show(PersonCenterActivity.this,"选择的日期不能超过当前日期",1500);
                    return;
                }

                birthday.setText(str);
                userBirth = str;
                closePopupWindows();
            }
        });
        Button cancel = (Button) view.findViewById(R.id.cancel);
        cancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                closePopupWindows();
            }
        });
        return view;
    }

    public void closePopupWindows(){
        menuWindow.dismiss();
        menuWindow=null;
        WindowManager.LayoutParams params=this.getWindow().getAttributes();
        params.alpha=1f;
        this.getWindow().setAttributes(params);
    }

    OnMyWheelScrollListener scrollListener = new OnMyWheelScrollListener() {

        @Override
        public void onScrollingStarted(MyWheelView wheel) {

        }

        @Override
        public void onScrollingFinished(MyWheelView wheel) {
            int n_year = year.getCurrentItem() + 1950;
            int n_month = month.getCurrentItem() + 1;
            initDay(n_year, n_month);
        }
    };

    private void initDay(int arg1, int arg2) {
        day.setAdapter(new NumericWheelAdapter(1, getDay(arg1, arg2), "%02d"));
    }

    private int getDay(int year, int month) {
        int day = 30;
        boolean flag = false;
        switch (year % 4) {
            case 0:
                flag = true;
                break;
            default:
                flag = false;
                break;
        }
        switch (month) {
            case 1:
            case 3:
            case 5:
            case 7:
            case 8:
            case 10:
            case 12:
                day = 31;
                break;
            case 2:
                day = flag ? 29 : 28;
                break;
            default:
                day = 30;
                break;
        }
        return day;
    }

    private void showPopwindow(View view) {
        menuWindow = new PopupWindow(view, WindowManager.LayoutParams.MATCH_PARENT, WindowManager.LayoutParams.WRAP_CONTENT);
        menuWindow.setFocusable(true);
        menuWindow.setBackgroundDrawable(new BitmapDrawable());
        WindowManager.LayoutParams params=this.getWindow().getAttributes();
        params.alpha=0.7f;//设置添加屏幕的背景透明度
        this.getWindow().setAttributes(params);
        menuWindow.showAtLocation(view, Gravity.CENTER_HORIZONTAL, 0, 0);
        menuWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                closePopupWindows();
            }
        });
    }

    Dialog dialog;
    private void showSelectPictureDialog() {
        dialog = new Dialog(this);
        dialog.setCanceledOnTouchOutside(false);
        Window window = dialog.getWindow();
        window.setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
        WindowManager.LayoutParams attributes = window.getAttributes();
        dialog.setContentView(R.layout.dialog_select_iconpath);
        WindowManager windowManager = getWindowManager();
        Display display = windowManager.getDefaultDisplay();
        WindowManager.LayoutParams lp = dialog.getWindow().getAttributes();
        lp.gravity = Gravity.BOTTOM;
        lp.width = WindowManager.LayoutParams.MATCH_PARENT;
        dialog.getWindow().setAttributes(lp);
        Button btnCancel = (Button) dialog.findViewById(R.id.cancle);
        Button btnCup = (Button) dialog.findViewById(R.id.cup_pic);
        Button btnSelect = (Button) dialog.findViewById(R.id.select_picBox);
        btnCancel.setOnClickListener(this);
        btnCup.setOnClickListener(this);
        btnSelect.setOnClickListener(this);
        dialog.show();
    }


    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ButterKnife.bind(this);
        inflater = (LayoutInflater) this.getSystemService(LAYOUT_INFLATER_SERVICE);
        userName=getIntent().getStringExtra("nickName");
        userheadImg=getIntent().getStringExtra("sheadImg");
        userBirth=getIntent().getStringExtra("birthDay");
        userSex=getIntent().getIntExtra("sex",1);
        mineBitmap = getIntent().getParcelableExtra("bitmap");
        /*Glide.with(this).load(OKUtilAPI.imgBaseUrl+userheadImg)
                .placeholder(R.mipmap.src)
                .into(headimg);*/
        try{

        if(!TextUtils.isEmpty(userName)){
            nickname.setText(URLDecoder.decode(userName,"utf-8"));
        }
        }catch (Exception e){
            e.printStackTrace();
        }
        if(!TextUtils.isEmpty(userBirth)){
            birthday.setText(userBirth);
        }
        if(userSex==0){
            sex.setText("女");
        }
        if(userSex==1){
            sex.setText("男");
        }
        if (mineBitmap == null){
            if(!TextUtils.isEmpty(userheadImg)){
                if(userheadImg.contains("http")){
                    Glide.with(this).load(userheadImg).into(headimg);
                }else{
                    Glide.with(this).load(OKUtilAPI.imgBaseUrl + userheadImg).into(headimg);
                }
            }
        }
        else {
            headimg.setImageBitmap(mineBitmap);
        }

    }
    
    Bitmap bitmap;
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode){
            case SELECT_FROM_GALLERY_REQUEST_CODE:
                if (data == null) {
                    return;
                }
                cropImage(data.getData());
                break;

            case CROP_PICTURE:
                if (data == null) {
                    return;
                }
                bitmap = data.getExtras().getParcelable("data");
                try {
                    Uri u = Uri.parse(MediaStore.Images.Media.insertImage(getContentResolver(), bitmap, null, null));
                    String[] projection = {MediaStore.Images.Media.DATA};
                    Cursor query = MediaStore.Images.Media.query(getContentResolver(), u, projection);
                    int column_index = query.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);// 将光标移至开头,这个很重要，不小心很容易引起越界
                    query.moveToFirst();// 最后根据索引值获取图片路径
                    headimg.setImageBitmap(bitmap);
                    path = query.getString(column_index);
                } catch (IllegalArgumentException e) {
                    e.printStackTrace();
                }
                break;

            case TAKE_PHOTO_REQUEST_CODE:
                if (resultCode == RESULT_OK) {
                    cropImage(uri);
                }
                break;

            case  TONICKNAME :
                if (resultCode == 0x188){
                    userName = data.getStringExtra("nickName");
                    nickname.setText(userName);
                }
                break;
        }
    }
}
